
package com.wobaby.util;

import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.wobaby.util.log.Log;
import com.wobaby.util.xml.XMLDocument;
import com.wobaby.util.xml.XMLElement;

// Referenced classes of package com.wobaby:
//            BCConfigRuleVO, ObjectEncoder

public class ValueObjectTransformer
{

    public ValueObjectTransformer()
    {
    }

    public static List transform(InputStream in, Object voTypes[])
        throws Exception
    {
        XMLDocument doc = new XMLDocument(in);
        XMLElement root = doc.getCoreElement();
        List ret = new ArrayList();
        for(int i = 0; i < voTypes.length; i++)
        {
            Object voType = voTypes[i];
            String voName = StringUtils.stripPackageName(voType.getClass().getName());
            Log.getLog("exporting").trace(com.wobaby.util.ValueObjectTransformer.class, "voName : " + voName);
            List elements = root.getSubelements(voName);
            for(int k = 0; elements != null && k < elements.size(); k++)
            {
                Object ob = null;
                
                    ob = voType.getClass().newInstance();
                XMLElement2VO((XMLElement)elements.get(k), ob);
                ret.add(ob);
            }

        }

        return ret;
    }

    public static void XMLElement2VO(XMLElement em, Object target)
        throws IllegalAccessException, ParseException
    {
        String voClassName = target.getClass().getName();
        if(voClassName.indexOf(em.getName()) < 0)
            throw new RuntimeException("VO type mismatching. Expecting " + voClassName + ", found " + em.getName());
        Field fields[] = target.getClass().getDeclaredFields();
        
        for(int i = 0; i < fields.length; i++)
        {
            Field field = fields[i];
            field.setAccessible(true);
            String name = field.getName();
            Log.getLog("exporting").trace(com.wobaby.util.ValueObjectTransformer.class, "Setting field : " + field);
            if(name.startsWith("m_"))
                name = name.substring(2);
            XMLElement xe = em.getSingleSubelement(StringUtils.capitalize(name));
            if(xe == null)
            {
                Log.getLog("exporting").trace(com.wobaby.util.ValueObjectTransformer.class, "Value is null ");
            } else
            {
                Log.getLog("exporting").trace(com.wobaby.util.ValueObjectTransformer.class, "Value = " + xe.getText());
                setValue(target, field, xe.getText());
            }
        }

    }

    static void setValue(Object vo, Field field, String strval)
        throws IllegalAccessException, ParseException
    {
        if(strval == null)
            return;
        String fieldClassName = field.getType().getName();
        Log.getLog("exporting").debug(com.wobaby.util.ValueObjectTransformer.class, "Field class: " + fieldClassName);
        if(fieldClassName.indexOf("Long") >= 0)
            field.set(vo, new Long(strval));
        else
        if(fieldClassName.indexOf("Integer") >= 0)
            field.set(vo, new Integer(strval));
        else
        if(fieldClassName.indexOf("Short") >= 0)
            field.set(vo, new Short(strval));
        else
        if(fieldClassName.indexOf("Float") >= 0)
            field.set(vo, new Float(strval));
        else
        if(fieldClassName.indexOf("Double") >= 0)
            field.set(vo, new Double(strval));
        else
        if(fieldClassName.indexOf("Boolean") >= 0)
            field.set(vo, new Boolean(strval));
        else
        if(fieldClassName.equals("long"))
            field.setLong(vo, (new Long(strval)).longValue());
        else
        if(fieldClassName.equals("int"))
            field.setInt(vo, (new Integer(strval)).intValue());
        else
        if(fieldClassName.equals("short"))
            field.setShort(vo, (new Short(strval)).shortValue());
        else
        if(fieldClassName.equals("float"))
            field.setFloat(vo, (new Float(strval)).floatValue());
        else
        if(fieldClassName.equals("double"))
            field.setDouble(vo, (new Double(strval)).doubleValue());
        else
        if(fieldClassName.equals("boolean"))
        {
            String fieldName = field.getName();
            if(fieldName.equals("useRegexp") || fieldName.equals("exactOrder"))
            {
                if(strval.equals("Y"))
                    field.setBoolean(vo, true);
                else
                    field.setBoolean(vo, false);
            } else
            {
                field.setBoolean(vo, (new Boolean(strval)).booleanValue());
            }
        } else
       /* if(fieldClassName.indexOf("Date") >= 0)
            field.set(vo, DateUtil.parse(strval, YYYY_MM_DD_HH_MM_ss_SSS));
        else*/
        if(fieldClassName.indexOf("List") >= 0)
        {
            List list = new ArrayList();
            if(strval.indexOf("<![CDATA[") != -1)
                list.add(strval.substring("<![CDATA[".length(), strval.length() - "]]>".length()));
            else
                list.add(strval);
            field.set(vo, list);
        } else
        {
            strval = strval.replaceAll("&lt;", "<");
            strval = strval.replaceAll("&amp;", "&");
            field.set(vo, strval);
        }
    }

    public static String marshalValueObject(List vos)
        throws IllegalAccessException
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            Element root = document.createElement("rn-export");
            document.appendChild(root);
            for(int k = 0; k < vos.size(); k++)
            {
                Object vo = vos.get(k);
                String voClassName = StringUtils.stripPackageName(vo.getClass().getName());
                Element voRoot = document.createElement(voClassName);
                root.appendChild(voRoot);
                Field fields[] = vo.getClass().getDeclaredFields();
                for(int i = 0; i < fields.length; i++)
                {
                    Field field = fields[i];
                    field.setAccessible(true);
                    String fieldName = StringUtils.capitalize(field.getName());
                    Object val = field.get(vo);
                    if(val == null)
                    {
                        Log.getLog("exporting").trace(com.wobaby.util.ValueObjectTransformer.class, fieldName + " is null, skip");
                    } else
                    {
                        String value = toString(val, vo);
                        Element ch = document.createElement(fieldName);
                        ch.appendChild(document.createTextNode(value));
                        voRoot.appendChild(ch);
                    }
                }

            }

            root.normalize();
            StringWriter out = new StringWriter();
            outputXMLDoc(document, out);
            return out.toString();
        }
        catch(ParserConfigurationException pce)
        {
            Log.getLog("exporting").error(com.wobaby.util.ValueObjectTransformer.class, "ParserConfigurationException thrown: " + pce.getMessage());
            throw new RenditionUncheckedException(pce);
        }
    }

    static String toString(Object ob, Object vo)
    {
        //if(ob == null)
            return "";
       /* if(ob instanceof Date)
            return DateUtil.format((Date)ob, YYYY_MM_DD_HH_MM_ss_SSS);*/
        /*if((ob instanceof List) && (vo instanceof RuleConditionVO))
        {
            StringBuilder buffer = new StringBuilder();
            List list = (ArrayList)ob;
            buffer.append("<![CDATA[");
            for(int i = 0; i < list.size(); i++)
                buffer.append("<operand>").append(list.get(i)).append("</operand>");

            buffer.append("]]>");
            return buffer.toString();
        } else
        {*/
            //return ObjectEncoder.toString(ob);
        //}
    }

    public static void outputXMLDoc(Document doc, Writer out)
    {
        try
        {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(out);
            transformer.setOutputProperty("indent", "yes");
            transformer.setOutputProperty("encoding", "ISO-8859-1");
            transformer.transform(source, result);
            Log.getLog("exporting").trace(com.wobaby.util.ValueObjectTransformer.class, "option written back to file");
        }
        catch(TransformerConfigurationException tce)
        {
            Log.getLog("exporting").error(com.wobaby.util.ValueObjectTransformer.class, "TransformerConfigurationException thrown: " + tce.getMessage());
            throw new RenditionUncheckedException(tce);
        }
        catch(TransformerException te)
        {
            Log.getLog("exporting").error(com.wobaby.util.ValueObjectTransformer.class, "TransformerException thrown: " + te.getMessage());
            throw new RenditionUncheckedException(te);
        }
    }

    public static Document createNewDocument(String rootElementName)
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            Element root = document.createElement(rootElementName);
            document.appendChild(root);
            return document;
        }
        catch(ParserConfigurationException pce)
        {
            Log.getLog("exporting").error(com.wobaby.util.ValueObjectTransformer.class, "ParserConfigurationException thrown: " + pce.getMessage());
            throw new RenditionUncheckedException(pce);
        }
    }

    public static final SimpleDateFormat YYYY_MM_DD_HH_MM_ss_SSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    public static final String CDATA_START = "<![CDATA[";
    public static final String CDATA_END = "]]>";

}